package com.Alan.servlet.supplier;

import com.Alan.pojo.Role;
import com.Alan.pojo.Supplier;
import com.Alan.pojo.User;
import com.Alan.service.role.RoleServiceImpl;
import com.Alan.service.supplier.SupplierService;
import com.Alan.service.supplier.SupplierServiceImpl;
import com.Alan.service.user.UserServiceImpl;
import com.Alan.util.Constants;
import com.Alan.util.Paging;
import com.Alan.util.UtilsAlan;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

public class SupServlet extends HttpServlet {
    
    public SupServlet(){super();}

    @Override
    public void destroy() {
        super.destroy();
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        System.out.println("method : " + method);
        
        if (!StringUtils.isNullOrEmpty(method)){
            switch (method){
                case "getSupList":
                    this.getSupList(req, resp);
                    break;
                case "supInformation":
                    this.supInformation(req, resp);
                    break;
                case "updateSup":
                    this.updateSup(req, resp);
                    break;
                case "updateSupSubmit":
                    this.updateSupSubmit(req, resp);
                    break;
                case "deleteSup":
                    this.deleteSup(req, resp);
                    break;
                case "addSup":
                    this.addSup(req, resp);
                    break;
                case "supExist":
                    this.supExist(req, resp);
                    break;

            }
        }
    }

    private void getSupList(HttpServletRequest req, HttpServletResponse resp) {
        Paging paging = new Paging();

        String supName = req.getParameter("querySupName");
        String contacts  = req.getParameter("querySupContacts");
        String pageIndex = req.getParameter("pageIndex");

        if (StringUtils.isNullOrEmpty(supName)){
            supName = "";
        }
        if (StringUtils.isNullOrEmpty(contacts)){
            contacts = "";
        }
        if (!StringUtils.isNullOrEmpty(pageIndex)) {
            paging.setPageIndex(Integer.parseInt(pageIndex));
        }

//        获取供应商列表
        SupplierService supplierService = new SupplierServiceImpl();
        List<Supplier> supList = supplierService.getSupList(supName, contacts, paging.getStartRow(), paging.getPageRows());
        //        获取用户总数并添加到Paging
        int supCount = supplierService.getSupCount(supName, contacts);
        paging.setAllSize(supCount);

//        返回前端数据
        req.setAttribute("supList", supList);
        req.setAttribute("pageCount", paging.getPageCount());
        req.setAttribute("allSize", paging.getAllSize());
        req.setAttribute("pageIndex", paging.getPageIndex());


//        返回前端
        try {
            req.getRequestDispatcher(req.getContextPath() + "/JSP/supplierList.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR:SupServlet -> getSupList");
        }

    }

    private void supInformation(HttpServletRequest req, HttpServletResponse resp) {
        int supId = Integer.parseInt(req.getParameter("supId"));
        SupplierService supplierService = new SupplierServiceImpl();
        Supplier sup = supplierService.getSupInformation(supId);

        req.setAttribute("sup", sup);

        try {
            req.getRequestDispatcher(req.getContextPath() + "/JSP/supplierInformation.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR:SupServlet -> supInformation -> Line(107)");
        }
    }

    private void updateSup(HttpServletRequest req, HttpServletResponse resp) {
        int userId = Integer.parseInt(req.getParameter("supId"));
        SupplierService supplierService = new SupplierServiceImpl();
        Supplier sup = supplierService.getSupInformation(userId);
        req.setAttribute("sup", sup);
        try {
            req.getRequestDispatcher(req.getContextPath() + "/JSP/supplierUpdate.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR:SupServlet -> updateSup");
        }
    }

    private void updateSupSubmit(HttpServletRequest req, HttpServletResponse resp) {Supplier sup = new Supplier();
        sup.setId(Integer.parseInt(req.getParameter("supId")));
        sup.setSupCode(req.getParameter("supCode"));
        sup.setSupName(UtilsAlan.transCoding(req.getParameter("supName"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        sup.setContacts(UtilsAlan.transCoding(req.getParameter("contacts"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        sup.setGender(UtilsAlan.transCoding(req.getParameter("gender"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        sup.setAge(Integer.parseInt(req.getParameter("age")));
        sup.setAddress(UtilsAlan.transCoding(req.getParameter("address"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        sup.setPhone(req.getParameter("phone"));
        sup.setDescribe(UtilsAlan.transCoding(req.getParameter("describe"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        sup.setModifyByUserCode(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getUserCode());
        sup.setModifyByUserName(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getUserName());
        sup.setModifyDate(UtilsAlan.strToSqlDate(UtilsAlan.getNowDateStr(), true));

        SupplierService supplierService = new SupplierServiceImpl();

        if (supplierService.updateSup(sup)){
            try {
                resp.sendRedirect(req.getContextPath() + "/JSP/sup.go?method=getSupList");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("ERROR:SupServlet -> updateSup -> 1");
            }
        }else {
            try {
                req.getRequestDispatcher(req.getContextPath() + "/JSP/supplierUpdate.jsp").forward(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("ERROR:SupServlet -> updateSup -> 2");
            }
        }
    }

    private void deleteSup(HttpServletRequest req, HttpServletResponse resp) {
        int supId = Integer.parseInt(req.getParameter("supId"));
        SupplierService supplierService = new SupplierServiceImpl();

        supplierService.deleteSup(supId);

        try {
            resp.sendRedirect(req.getContextPath() + "/JSP/sup.go?method=getSupList");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR:SupServlet -> deleteSup");
        }
    }

    private void addSup(HttpServletRequest req, HttpServletResponse resp) {
        Supplier sup = new Supplier();
        sup.setSupCode(req.getParameter("supCode"));
        sup.setSupName(req.getParameter("supName"));
        sup.setContacts(req.getParameter("contacts"));
        sup.setGender(UtilsAlan.transCoding(req.getParameter("supGender"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        sup.setAge(Integer.parseInt(req.getParameter("age")));
        sup.setAddress(UtilsAlan.transCoding(req.getParameter("address"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        sup.setPhone(req.getParameter("phone"));
        sup.setDescribe(UtilsAlan.transCoding(req.getParameter("describe"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        sup.setCreatedByUserCode(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getUserCode());
        sup.setCreatedByUserName(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getUserName());
        sup.setCreationDate(UtilsAlan.strToSqlDate(UtilsAlan.getNowDateStr(), true));

        SupplierService supplierService = new SupplierServiceImpl();

        if (supplierService.addSup(sup)){
            try {
                resp.sendRedirect(req.getContextPath() + "/JSP/sup.go?method=getSupList");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("ERROR:SupServlet -> addSup -> 1");
            }
        }else {
            try {
                req.getRequestDispatcher(req.getContextPath() + "/JSP/supplierAdd.jsp").forward(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("ERROR:SupServlet -> addSup -> 2");
            }
        }
    }

    private void supExist(HttpServletRequest req, HttpServletResponse resp) {
        String supCode = req.getParameter("supCode");
        HashMap<String, String> resultMap = new HashMap<String, String>();


        if (!StringUtils.isNullOrEmpty(supCode)){
            SupplierService supplierService = new SupplierServiceImpl();
            if (supplierService.supExist(supCode)) {
                resultMap.put("supCode", "exist");
            } else {
                resultMap.put("supCode", "notExist");
            }
        } else {
            resultMap.put("supCode", "exist");
        }

        System.out.println(resultMap.get("supCode"));

        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        resp.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = null;
        try {
            outPrintWriter = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("UserServlet -> verifyUserCodeExist");
        }
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流


    }
}
